package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-28
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {
    @Autowired
    @Lazy
    private IAuditService auditService;
    @Autowired
    private IWmNewsMaterialService iWmNewsMaterialService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        //判断是否有登录人
        User user = UserThreadLocalUtil.get();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构造条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //开始时间
        if(dto.getBeginPubDate()!=null){
            queryWrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
        }
        //结束时间
        if(dto.getEndPubDate()!=null){
            queryWrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        }
        //频道
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //关键字
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //排序 当前登录人
        queryWrapper.eq(WmNews::getUserId,user.getUserId());
        queryWrapper.orderByDesc(WmNews::getPublishTime);

        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> page1 = this.page(page,queryWrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //判断是否有登录人
        User user = UserThreadLocalUtil.get();
        if(user == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //如果有判断是否有id
        if(dto.getId()!=null){
            //根据自媒体文章id,删除已关联的素材关系
            deleteRelation(dto.getId());
        //构建自媒体文章对象
            WmNews wmNews = new WmNews();
            BeanUtils.copyProperties(dto,wmNews);
            wmNews.setUserId(user.getUserId());
            wmNews.setCreatedTime(new Date());
//            wmNews.setEnable(true);
            //dto中的images是集合,表中要的是一个字符串
            wmNews.setImages(JSON.toJSONString(dto.getImages()));
            //从内容中获取所有的图片
            List<ImageDto> iages = getIagesFromContent(dto.getContent());
            if(dto.getType()==-1){
                //封面图片是从文章内容获取 1  3  无图
                int size = iages.size();
                if(size<=0){//无图
                    wmNews.setType(0);
                }else if(size>0&&size<3){
                    wmNews.setType(1);
                    //截图内容图片中的一个对象作为封面
                    List<ImageDto> imageDtos = iages.subList(0, 1);
                    wmNews.setImages(JSON.toJSONString(imageDtos));
                }else {
                    wmNews.setType(3);
                    List<ImageDto> imageDtoList = iages.subList(0, 3);
                    wmNews.setImages(JSON.toJSONString(imageDtoList));
                }
            }
        //新增文章或者修改文章
            this.saveOrUpdate(wmNews);//自动判读是否有id ,如果有就修改,如果没就新增
            //判断是否为草稿
            if(dto.getStatus()==1){//提交为1
                //保存文章内容图片和素材之间的关系
                saveRelation(iages,wmNews.getId(),0);
                List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
                saveRelation(imageDtoList,wmNews.getId(),1);
                auditService.audit(wmNews);
            }
        }
        return ResponseResult.okResult();
    }



    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断是否又文章id
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据id是否能查询出对象
        WmNews wmNews = this.getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断这个自媒体文章是否是当前登录人发布的
        if(user.getUserId()!=wmNews.getUserId()){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //判断文章是否为发布状态
        if(wmNews.getStatus()!=9){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmNews.setEnable(dto.getEnable()==1?true:false);
        this.updateById(wmNews);
        Map map = new HashMap();
        map.put("articled",wmNews.getArticleId());
        map.put("enable",dto.getEnable()==1?true:false);
        kafkaTemplate.send(topicUpDownTopic,JSON.toJSONString(map));
        return ResponseResult.okResult();
    }
    @Value("&{topic.upDownTopic}")
    private String topicUpDownTopic;

    //保存文章内容图片.封面图片与素材的关系
    private void saveRelation(List<ImageDto> iages, Integer id, int i) {
        int a = 0;
        for (ImageDto imageDto : iages) {
            WmNewsMaterial newsMaterial = new WmNewsMaterial();
            newsMaterial.setMaterialId(imageDto.getId());
            newsMaterial.setNewsId(id);
            newsMaterial.setType(i);
            newsMaterial.setOrd(a);
            a++;
            iWmNewsMaterialService.save(newsMaterial);
        }

    }

    //从内容中获取所有图片
    private List<ImageDto> getIagesFromContent(String content) {
        List<ImageDto> dtoList = new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if(contentDto.getType().equals("image")){
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                dtoList.add(imageDto);
            }
        }
        return dtoList;
    }
        //根据自媒体文章id  删除已关联的素材关系
    private void deleteRelation(Integer id) {
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,id);
        iWmNewsMaterialService.remove(queryWrapper);
    }
}
